package fu.capstone.hanoicityguide.presentation.activity;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.mapsforge.map.android.graphics.AndroidGraphicFactory;

import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;
//import fu.capstone.hanoicityguide.HotelFragment;
//import fu.capstone.hanoicityguide.PagesFragment;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.model.NavDrawerItem;
import fu.capstone.hanoicityguide.common.utility.InternetSetting;
import fu.capstone.hanoicityguide.common.vgservice.VoiceGuidanceService;
import fu.capstone.hanoicityguide.dataaccess.webservice.WebServiceDAOImpl;
import fu.capstone.hanoicityguide.presentation.adapter.NavDrawerListAdapter;
import fu.capstone.hanoicityguide.presentation.fragment.attraction.DetailAttractionFragment;
import fu.capstone.hanoicityguide.presentation.fragment.attraction.ListAttractionFragment;
import fu.capstone.hanoicityguide.presentation.fragment.commondialogue.ListCommonDialogueFragment;
import fu.capstone.hanoicityguide.presentation.fragment.food.ListFoodFragment;
import fu.capstone.hanoicityguide.presentation.fragment.holiday.ListHolidayFragment;
import fu.capstone.hanoicityguide.presentation.fragment.home.HomeFragment;
//import fu.capstone.hanoicityguide.HotelFragment;
//import fu.capstone.hanoicityguide.PagesFragment;
//import fu.capstone.hanoicityguide.RestaurantFragment;
//import fu.capstone.hanoicityguide.WhatsHotFragment;
//import fu.capstone.hanoicityguide.presentation.activity.
import fu.capstone.hanoicityguide.presentation.fragment.hotel.ListHotelFragment;
import fu.capstone.hanoicityguide.presentation.fragment.itinerary.ListItineraryFragment;
import fu.capstone.hanoicityguide.presentation.fragment.nearby.ListNearbyPlaceFragment;
import fu.capstone.hanoicityguide.presentation.fragment.nearby.NearbyOnlineMapFragment;
import fu.capstone.hanoicityguide.presentation.fragment.nightlife.ListNightLifeFragment;
import fu.capstone.hanoicityguide.presentation.fragment.restaurant.ListRestaurantFragment;
import fu.capstone.hanoicityguide.presentation.fragment.tourprovider.ListTourProviderFragment;

public class MainActivity extends Activity implements
		FragmentManager.OnBackStackChangedListener {

	private DrawerLayout mDrawerLayout;
	private ExpandableListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

	// nav drawer title
	private CharSequence mDrawerTitle;

	// used to store app title
	private CharSequence mTitle;

	// slide menu items
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;
	private String[] moreTitle;
	private ArrayList<NavDrawerItem> navDrawerItems;
	private NavDrawerListAdapter adapter;
	private UiLifecycleHelper uiHelper;
	HashMap<String, List<String>> listDataChild;
	private Fragment fragment;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
	        PackageInfo info = getPackageManager().getPackageInfo(
	                "fu.capstone.hanoicityguide", 
	                PackageManager.GET_SIGNATURES);
	        for (Signature signature : info.signatures) {
	            MessageDigest md = MessageDigest.getInstance("SHA");
	            md.update(signature.toByteArray());
	            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
	            }
	    } catch (NameNotFoundException e) {

	    } catch (NoSuchAlgorithmException e) {

	    }
		
		getActionBar().setBackgroundDrawable(
				new ColorDrawable(Color.parseColor("#0099CC")));
		mTitle = mDrawerTitle = getTitle();

		moreTitle = getResources().getStringArray(R.array.more_items);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ExpandableListView) findViewById(R.id.slidemenu);

		// initialize variables
		navDrawerItems = new ArrayList<NavDrawerItem>();
		listDataChild = new HashMap<String, List<String>>();

		navMenuTitles = new String[getResources().getStringArray(
				R.array.slide_menu_items).length];
		System.arraycopy(getResources()
				.getStringArray(R.array.slide_menu_items), 0, navMenuTitles, 0,
				getResources().getStringArray(R.array.slide_menu_items).length);
		navMenuIcons = getResources()
				.obtainTypedArray(R.array.slide_menu_icons);

		for (int i = 0; i < navMenuTitles.length; i++) {
			navDrawerItems.add(new NavDrawerItem(navMenuTitles[i], navMenuIcons
					.getResourceId(i, -1)));
		}

		navMenuIcons.recycle();

		// Navigation Drawer of Flight starts
		// navDrawerItems.add(new NavDrawerItem(("Home"), R.drawable.ic_home));
		// navDrawerItems.add(new NavDrawerItem(("Attractions"),
		// R.drawable.ic_home));
		// navDrawerItems.add(new NavDrawerItem(("Hotels"),
		// R.drawable.ic_home));
		// navDrawerItems.add(new NavDrawerItem(("More"), R.drawable.ic_home));

		// listDataChild.put("Home", new ArrayList<String>());
		// listDataChild.put("Attractions", new ArrayList<String>());
		// listDataChild.put("Hotels", new ArrayList<String>());

		for (int i = 0; i < (navMenuTitles.length - 1); i++) {
			listDataChild.put(navMenuTitles[i], new ArrayList<String>());
		}

		listDataChild.put("More", Arrays.asList(moreTitle));

		adapter = new NavDrawerListAdapter(this, navDrawerItems, listDataChild);
		// setting list adapter
		mDrawerList.setAdapter(adapter);
		mDrawerList.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);

		// enabling action bar app icon and behaving it as toggle button
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {

			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				// onPrepareOptionsMenu(menu);
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				invalidateOptionsMenu();
			}
		};
		// mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			// on first time display view for first nav item
			displayView(0);
		}
		getFragmentManager().addOnBackStackChangedListener(this);

		// set event on nav items click
		mDrawerList
				.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

					@Override
					public boolean onGroupClick(ExpandableListView parent,
							View v, int groupPosition, long id) {
						// TODO Auto-generated method stub
						if (groupPosition != 8)
							displayView(groupPosition);
						return false;
					}
				});

		mDrawerList
				.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

					@Override
					public boolean onChildClick(ExpandableListView arg0,
							View arg1, int arg2, int arg3, long arg4) {
						// TODO Auto-generated method stub

						displayChildView(arg2, arg3);
						return false;
					}
				});

		/* This part is use to start the service, remember to call stopService */
		// Intent service_intent = new Intent(this, VoiceGuidanceService.class);
		// startService(service_intent);

	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);

		int placeID = intent.getIntExtra("PlaceID", -1);

		if (placeID != -1) {
//			// Fragment listFragment = new
//			// ListAttractionFragment(mDrawerLayout);
//			// FragmentManager fragmentManager = getFragmentManager();
//			// FragmentTransaction fTransaction = fragmentManager
//			// .beginTransaction();
//			// fTransaction.addToBackStack(null);
//			// // Log.v("Add fragment ",
//			// navDrawerItems.get(position).getTitle());
//			// //
//			// fTransaction.addToBackStack(navDrawerItems.get(position).getTitle());
//			// fTransaction.replace(R.id.frame_container,
//			// listFragment).commit();
			
			Fragment fragment = new DetailAttractionFragment(placeID);
			FragmentManager fragmentManager = getFragmentManager();
			FragmentTransaction fTransaction = fragmentManager
					.beginTransaction();
			fTransaction.addToBackStack(null);
			fTransaction.replace(R.id.frame_container, fragment).commit();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		AndroidGraphicFactory.createInstance(this.getApplication());
		Intent receiveBrowsePlaceIntent = getIntent();
		int placeID = receiveBrowsePlaceIntent.getIntExtra("PlaceID", -1);

		if (placeID != -1) {
//			// Fragment listFragment = new
//			// ListAttractionFragment(mDrawerLayout);
//			// FragmentManager fragmentManager = getFragmentManager();
//			// FragmentTransaction fTransaction = fragmentManager
//			// .beginTransaction();
//			// fTransaction.addToBackStack(null);
//			//
//			// // Log.v("Add fragment ",
//			// navDrawerItems.get(position).getTitle());
//			// //
//			// fTransaction.addToBackStack(navDrawerItems.get(position).getTitle());
//			// fTransaction.replace(R.id.frame_container,
//			// listFragment).commit();
//
			Fragment fragment = new DetailAttractionFragment(placeID);
			FragmentManager fragmentManager = getFragmentManager();
			FragmentTransaction fTransaction = fragmentManager
					.beginTransaction();
			fTransaction.addToBackStack(null);
			fTransaction.replace(R.id.frame_container, fragment).commit();
		}
		
		receiveBrowsePlaceIntent.removeExtra("PlaceID");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		LocalBroadcastManager.getInstance(this).unregisterReceiver(
				VoiceGuidanceService.mRegisterReceiver);
		Log.v("on destroy main activity", "destroy receiver");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// MenuInflater inflater = getMenuInflater();
		// inflater.inflate(R.menu.main, menu);

		// Associate searchable configuration with the SearchView
		// SearchManager searchManager = (SearchManager)
		// getSystemService(Context.SEARCH_SERVICE);
		// SearchView searchView = (SearchView)
		// menu.findItem(R.id.action_search)
		// .getActionView();
		// searchView.setSearchableInfo(searchManager
		// .getSearchableInfo(getComponentName()));

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (getFragmentManager().getBackStackEntryCount() < 1) {
			// toggle nav drawer on selecting action bar app icon/title
			if (mDrawerToggle.onOptionsItemSelected(item)) {
				return true;
			}
		} else {
			// Handle action bar actions click
			switch (item.getItemId()) {
			case android.R.id.home:
				getFragmentManager().popBackStack();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
		return false;

	}

	/* *
	 * Called when invalidateOptionsMenu() is triggered
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		// menu.findItem(R.id.action_search).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		try {
			FragmentManager fm = getFragmentManager();
			if (fm.getBackStackEntryCount() > 0) {
				String tag = fm.getBackStackEntryAt(
						fm.getBackStackEntryCount() - 1).getName();

				Fragment fragment = fm.findFragmentByTag(tag);

				Log.v("Current Fragment", tag);
				int menuIndex = 0;
				for (int i = 0; i < navMenuTitles.length; i++) {
					if (navMenuTitles[i].equals(tag)) {
						menuIndex = i;
						break;
					}
				}
				// update selected item and title, then close the drawer
				mDrawerList.setItemChecked(menuIndex, true);
				mDrawerList.setSelection(menuIndex);
				// setTitle(navMenuTitles[menuIndex]);
			} else {
				// finish();
			}
		} catch (Exception e) {
		}
	}

	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * */
	private void displayView(int position) {
		// update the main content by replacing fragments
		fragment = null;
		// InternetSetting internetSetting = new InternetSetting(this);
		switch (position) {
		case 0:
			fragment = new HomeFragment(mDrawerLayout);
			break;
		case 1:
			fragment = new ListAttractionFragment(mDrawerLayout);
			break;
		case 2:
			fragment = new ListHotelFragment(mDrawerLayout);
			break;
		case 3:
			fragment = new ListRestaurantFragment(mDrawerLayout);
			break;
		case 4:
			fragment = new ListNightLifeFragment(mDrawerLayout);
			break;
		case 5:
			fragment = new ListItineraryFragment(mDrawerLayout);
			break;
		case 6:

			// if internet = false + billing purchased => new
			// NearbyOfflineMapFragment
			fragment = new ListNearbyPlaceFragment(mDrawerLayout);
			break;
		case 7:
			fragment = new ListTourProviderFragment(mDrawerLayout);
			break;

		default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getFragmentManager();
			FragmentTransaction fTransaction = fragmentManager
					.beginTransaction();
			// Log.v("Add fragment ", navDrawerItems.get(position).getTitle());
			// fTransaction.addToBackStack(navDrawerItems.get(position).getTitle());
			fTransaction.replace(R.id.frame_container, fragment).commit();

			// update selected item and title, then close the drawer
			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			// error in creating fragment
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	private void displayChildView(int groupPosition, int childPosition) {

		Fragment fragment = null;
		switch (childPosition) {
		case 0:
			fragment = new ListFoodFragment(mDrawerLayout);
			break;
		case 1:
			mDrawerLayout.closeDrawer(Gravity.LEFT);
			Intent i = new Intent(this, TransportationActivity.class);
			startActivity(i);
			break;
		case 2:
			fragment = new ListHolidayFragment(mDrawerLayout);
			break;
		case 3:
			fragment = new ListCommonDialogueFragment(mDrawerLayout);
			break;
		default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getFragmentManager();
			FragmentTransaction fTransaction = fragmentManager
					.beginTransaction();
			// Log.v("Add fragment ", navDrawerItems.get(position).getTitle());
			// fTransaction.addToBackStack(navDrawerItems.get(position).getTitle());
			fTransaction.replace(R.id.frame_container, fragment).commit();

			// update selected item and title, then close the drawer
			// mDrawerList.setItemChecked(childPosition, true);
			// mDrawerList.setSelection(childPosition);
			setTitle(listDataChild.get("More").get(childPosition));
			mDrawerList.setItemChecked(groupPosition + childPosition + 1, true);
			mDrawerList.setSelection(groupPosition + childPosition + 1);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			// error in creating fragment
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public void onBackStackChanged() {
		// TODO Auto-generated method stub
		int backStackCount = getFragmentManager().getBackStackEntryCount();
		FragmentManager fm = getFragmentManager();
		String tag = "";
		try {
			tag = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1)
					.getName();
		} catch (Exception e) {
			tag = "";
		}
		// Toast.makeText(MainActivity.this,
		// "Count MainActivity : " + backStackCount, Toast.LENGTH_LONG)
		// .show();

		// if (tag != null && tag.equals("ListPlace")) {
		// getActionBar().setDisplayShowHomeEnabled(true);
		// mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
		// } else {
		if (backStackCount >= 1) {
			getActionBar().setDisplayShowHomeEnabled(false);
			mDrawerLayout
					.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		} else {
			getActionBar().setDisplayShowHomeEnabled(true);
			mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
		}
		// }
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (fragment != null) {
			fragment.onActivityResult(requestCode, resultCode, data);
		}
	}
}
